package org.dromara.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.aspect.DataPermissionAspect;
import org.dromara.interceptor.PlusDataPermissionInterceptor;
import org.dromara.util.SpringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeansException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @ClassName EY-MybatisPlusConfiguration
 * @Description org.dromara.common.mybatis.config
 * @Author menyj
 * @Date 2025/4/3
 **/
@Slf4j
@Configuration
//@AutoConfiguration
//@AutoConfiguration(after = {TenantConfiguration.class})
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan("${mybatis-plus.mapperPackage}")
public class MybatisPlusConfiguration {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 多租户插件 必须放到第一位
        try {
//            TenantLineInnerInterceptor tenant = SpringUtils.getBean(TenantLineInnerInterceptor.class);
//            interceptor.addInnerInterceptor(tenant);
        } catch (BeansException ignore) {
            log.info("TenantLineInnerInterceptor", ignore);
        }
////        // 数据权限处理
        interceptor.addInnerInterceptor(dataPermissionInterceptor());
//        // 分页插件
//        interceptor.addInnerInterceptor(paginationInnerInterceptor());
//        // 乐观锁插件
//        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
        return interceptor;
    }

//    /**
//     * 分页插件，自动识别数据库类型
//     */
//    public PaginationInnerInterceptor paginationInnerInterceptor() {
//        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
//        // 分页合理化
//        paginationInnerInterceptor.setOverflow(true);
//        return paginationInnerInterceptor;
//    }

    /**
     * 乐观锁插件
     */
//    public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
//        return new OptimisticLockerInnerInterceptor();
//    }
//
    /**
     * 数据权限拦截器
     */
    public PlusDataPermissionInterceptor dataPermissionInterceptor() {
        return new PlusDataPermissionInterceptor(SpringUtils.getProperty("mybatis-plus.mapperPackage"));
    }

    /**
     * 数据权限切面处理器
     */
    @Bean
    public DataPermissionAspect dataPermissionAspect() {
        return new DataPermissionAspect();
    }
}
